import ast


def analyze_python_code(code):
    """分析 Python 代码结构"""
    tree = ast.parse(code)

    functions = []
    variables = []
    imports = []

    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef):
            functions.append(
                {
                    "name": node.name,
                    "args": [arg.arg for arg in node.args.args],
                    "line": node.lineno,
                }
            )
        elif isinstance(node, ast.Assign):
            for target in node.targets:
                if isinstance(target, ast.Name):
                    variables.append(target.id)
        elif isinstance(node, ast.Import):
            imports.extend([alias.name for alias in node.names])
        elif isinstance(node, ast.ImportFrom):
            imports.append(f"from {node.module}")

    return {"functions": functions, "variables": variables, "imports": imports}


# 使用示例
code = """
import os
from datetime import datetime

def process_data(data, threshold=10):
    result = []
    for item in data:
        if item > threshold:
            result.append(item * 2)
    return result

config = {'debug': True}
"""

analysis = analyze_python_code(code)
print(analysis)
